<template>
  <!--仓库-->
  <div class="bg-white" style="height: calc(100% - 96px)">
    <BasicForm @register="warehouseRegisterForm" class="!p-4">
      <template #privateKeySlot>
        <Upload name="file" :beforeUpload="upLoadChange">
          <Button>
            <Icon icon="material-symbols:upload" />
            上传文件
          </Button>
        </Upload>
      </template>
    </BasicForm>
  </div>
  <div class="h-16 bg-white w-full flex justify-end items-center mt-4">
    <Button
      class="mr-2"
      type="primary"
      danger
      :disabled="false"
      :loading="isLoading"
      v-show="deleteFlag"
      @click="deleteWarehouseClick"
      >删除</Button
    >
    <Button class="mr-2" type="primary" :loading="isLoading" @click="checkAccessClick"
      >检查访问权限</Button
    >
    <Button class="mr-2" type="primary" :loading="isLoading" @click="saveClick">保存</Button>
  </div>
</template>

<script setup lang="ts">
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { Button, Upload } from 'ant-design-vue';
  import { onMounted, ref } from 'vue';
  import { saveWarehouseItem } from '/@/api/thingsborad/settings/model/settingsModel';
  import {
    deleteRepositorySettings,
    editRepositorySettings,
    getCheckAccessSettings,
    getRepositorySettings,
    getSystemParams,
  } from '/@/api/thingsborad/settings/settings';
  import { useMessage } from '/@/hooks/web/useMessage';
  import Icon from '/@/components/Icon/src/Icon.vue';
  import { modalFormStyleSetting } from '/@/settings/thingsBoardDesign';
  import { useSystemStoreWithOut } from '/@/store/modules/thingsboard/systemParams';
  const userStore = useSystemStoreWithOut();
  let deleteFlag = ref<boolean>(false);
  let repositorySettingsData = ref<any>();
  let upLoadFile = ref<any>();
  let usernamePasswordFlag = ref<boolean>(true);
  let privateKeyPasswordFlag = ref<boolean>(true);
  let hasRepository = ref<boolean>(false);
  const isLoading = ref<boolean>(false);

  const props = defineProps({
    isSetting: {
      type: Boolean,
      default: false,
    },
  });

  // 生命周期函数
  onMounted(async () => {
    const systemParams = await getSystemParams();
    if (systemParams.hasRepository) {
      hasRepository.value = true;
      try {
        repositorySettingsData.value = await getRepositorySettings();
        usernamePasswordFlag.value = !(
          repositorySettingsData.value.username !== null &&
          repositorySettingsData.value.username !== ''
        );
        privateKeyPasswordFlag.value = !(
          repositorySettingsData.value.privateKeyFileName !== null &&
          repositorySettingsData.value.privateKeyFileName !== ''
        );
        setFieldsValue({
          repositoryUri: repositorySettingsData.value.repositoryUri,
          defaultBranch: repositorySettingsData.value.defaultBranch,
          username: repositorySettingsData.value.username,
          readOnlyOrCommit: [
            repositorySettingsData.value.readOnly && 'readOnly',
            repositorySettingsData.value.showMergeCommits && 'showMergeCommits',
          ],
          authMethod: repositorySettingsData.value.authMethod,
        });
        deleteFlag.value = true;
        // 根据需要处理数据并更新组件状态
      } catch (error) {
        deleteFlag.value = false;
      }
    }
  });
  // 表单内容 仓库
  const warehouseSchemas: FormSchema[] = [
    {
      field: 'repositoryUri',
      component: 'Input',
      label: '仓库 URL',
      required: true,
      componentProps: {
        placeholder: '请输入仓库 URL',
      },
    },
    {
      field: 'defaultBranch',
      component: 'Input',
      label: '默认分支名称',
      defaultValue: 'main',
      componentProps: {
        placeholder: '请输入默认分支名称',
      },
    },
    {
      field: 'readOnlyOrCommit',
      component: 'CheckboxGroup',
      label: '',
      componentProps: {
        options: [
          {
            label: '只读',
            value: 'readOnly',
          },
          {
            label: '显示合并提交',
            value: 'showMergeCommits',
          },
        ],
      },
      colProps: props.isSetting
        ? {
            span: 6,
            offset: 0,
            pull: 0,
            push: 1,
            style: {
              marginLeft: '25px',
            },
          }
        : {
            span: 6,
            offset: 0,
            pull: 0,
            push: 3,
          },
    },
    {
      field: 'authMethod',
      component: 'Select',
      label: '身份验证方法',
      required: true,
      defaultValue: 'USERNAME_PASSWORD',
      componentProps: {
        options: [
          {
            label: '密码/访问令牌',
            value: 'USERNAME_PASSWORD',
          },
          {
            label: '私钥',
            value: 'PRIVATE_KEY',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        return value.model.authMethod === 'PRIVATE_KEY';
      },
      field: 'privateKey',
      component: 'Input',
      slot: 'privateKeySlot',
      label: '私钥',
    },
    {
      ifShow: (value) => {
        let privateKeyPasswordToken;
        if (
          value.model.privateKeyPasswordCheck !== undefined &&
          value.model.privateKeyPasswordCheck[0] === 'privateKey'
        ) {
          privateKeyPasswordToken = true;
        }
        return (
          (privateKeyPasswordFlag.value || privateKeyPasswordToken) &&
          value.model.authMethod === 'PRIVATE_KEY'
        );
      },
      field: 'privateKeyPassword',
      component: 'InputPassword',
      label: '口令',
      componentProps: {
        placeholder: '请输入口令',
      },
    },
    {
      ifShow: () => {
        return !privateKeyPasswordFlag.value;
      },
      field: 'privateKeyPasswordCheck',
      component: 'CheckboxGroup',
      label: '',
      componentProps: {
        options: [
          {
            label: '更改密码',
            value: 'privateKey',
          },
        ],
      },
    },

    {
      ifShow: (value) => {
        return value.model.authMethod === 'USERNAME_PASSWORD';
      },
      field: 'username',
      component: 'Input',
      label: '用户名',
      componentProps: {
        placeholder: '请输入用户名',
      },
    },
    {
      ifShow: () => {
        return hasRepository.value;
      },
      field: 'usernameCheck',
      component: 'CheckboxGroup',
      label: '',
      componentProps: {
        options: [
          {
            label: '更改密码/访问令牌',
            value: 'password',
          },
        ],
      },
      colProps: props.isSetting
        ? {
            span: 6,
            offset: 0,
            pull: 0,
            push: 1,
            style: {
              marginLeft: '25px',
            },
          }
        : {
            span: 6,
            offset: 0,
            pull: 0,
            push: 3,
          },
    },
    {
      ifShow: (value) => {
        let flag = false;
        if (hasRepository.value) {
          if (value.model.usernameCheck && value.model.usernameCheck[0] === 'password') {
            flag = true;
          } else {
            flag = false;
          }
        } else {
          flag = true;
        }

        return value.model.authMethod === 'USERNAME_PASSWORD' && flag;
      },
      field: 'password',
      component: 'InputPassword',
      label: '密码/访问令牌',
      componentProps: {
        placeholder: '请输入密码',
      },
    },
  ];
  // 表单初始化
  const [warehouseRegisterForm, { validate, getFieldsValue, resetFields, setFieldsValue }] =
    useForm({
      ...modalFormStyleSetting,
      layout: 'horizontal',
      schemas: warehouseSchemas,
      baseColProps: {
        span: 12,
        offset: 12,
        pull: 12,
      },
      labelCol: {},
      labelWidth: 100,
      actionColOptions: {
        span: 24,
      },
      showActionButtonGroup: false,
    });
  const { createMessage, createConfirm } = useMessage();
  const upLoadChange = (file: File) => {
    // 文件读取
    const reader = new FileReader();
    reader.readAsText(file);
    //获取上传数据
    reader.addEventListener('load', () => {
      upLoadFile.value = {
        privateKeyFileName: file.name,
        privateKey: reader.result,
      };
    });
  };
  //删除点击事件
  function deleteWarehouseClick() {
    createConfirm({
      iconType: 'info',
      title: `确定要删除仓库设置吗？`,
      content: '请注意：确认后，仓库设置将被删除，版本控制功能将不可用。',
      onOk: async () => {
        try {
          isLoading.value = true;
          await deleteRepositorySettings();
          resetFields();
          hasRepository.value = false;
          deleteFlag.value = false;
          userStore.setHasRepository();
        } finally {
          isLoading.value = false;
        }
      },
    });
  }
  //检查访问权限点击事件
  async function checkAccessClick() {
    try {
      isLoading.value = true;
      // 表单验证
      await validate();
      //获取表单数据
      let fieldsValue = getFieldsValue();
      //请求参数填充
      let params: saveWarehouseItem = {
        repositoryUri: fieldsValue.repositoryUri,
        defaultBranch: fieldsValue.defaultBranch,
        authMethod: fieldsValue.authMethod,
        username: fieldsValue.username,
        password: fieldsValue.password,
        readOnly: false,
        showMergeCommits: false,
      };
      if (fieldsValue.readOnlyOrCommit) {
        params = Object.assign(params, {
          readOnly: fieldsValue.readOnlyOrCommit.includes('readOnly'),
          showMergeCommits: fieldsValue.readOnlyOrCommit.includes('showMergeCommits'),
        });
      }
      await getCheckAccessSettings(params);
      createMessage.success('检查访问权限成功');
      // 根据需要处理数据并更新组件状态
    } catch (error) {
      createMessage.error('权限认证失败，请检查输入信息');
    } finally {
      isLoading.value = false;
    }
  }
  //保存点击事件
  async function saveClick() {
    isLoading.value = true;
    try {
      //获取表单数据
      let fieldsValue = await validate();
      let params: saveWarehouseItem;
      // 请求参数填充
      if (fieldsValue.authMethod === 'PRIVATE_KEY') {
        params = {
          repositoryUri: fieldsValue.repositoryUri,
          defaultBranch:
            fieldsValue.defaultBranch === undefined ? 'main' : fieldsValue.defaultBranch,
          readOnly: fieldsValue?.readOnlyOrCommit?.includes('readOnly'),
          showMergeCommits: fieldsValue?.readOnlyOrCommit?.includes('showMergeCommits'),
          authMethod: fieldsValue.authMethod,
          privateKeyFileName: upLoadFile.value.privateKeyFileName,
          privateKey: upLoadFile.value.privateKey,
          privateKeyPassword: fieldsValue.privateKeyPassword,
        };
      } else {
        params = {
          repositoryUri: fieldsValue.repositoryUri,
          defaultBranch:
            fieldsValue.defaultBranch === undefined ? 'main' : fieldsValue.defaultBranch,
          readOnly: fieldsValue?.readOnlyOrCommit?.includes('readOnly'),
          showMergeCommits: fieldsValue?.readOnlyOrCommit?.includes('showMergeCommits'),
          authMethod: fieldsValue.authMethod,
          username: fieldsValue.username === undefined ? null : fieldsValue.username,
          password: fieldsValue.password === undefined ? null : fieldsValue.password,
        };
      }

      await editRepositorySettings(params);
      createMessage.success('保存成功');
      setFieldsValue({
        usernameCheck: undefined,
      });
      hasRepository.value = true;
      deleteFlag.value = true;
      isLoading.value = false;
      userStore.setHasRepository();
    } catch (error) {
      createMessage.error('权限认证失败，请检查输入信息');
    } finally {
      isLoading.value = false;
    }
  }
</script>
